package com.cloud.auth.config;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.cloud.auth.properties.AuthProperties;
import com.cloud.auth.properties.ClientsProperties;
import com.cloud.auth.service.UserDetailService;
import com.cloud.auth.translator.AuthWebResponseExceptionTranslator;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.builders.InMemoryClientDetailsServiceBuilder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

/**
 * @Description: OAuth2认证服务器相关的安全配置类
 * @Auther: zhangxun
 * @Date: 2020/8/7 14:22
 */
@Configuration
@EnableAuthorizationServer  //开启认证服务器相关配置。
public class AuthorizationServerConfigure extends AuthorizationServerConfigurerAdapter {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisConnectionFactory redisConnectionFactory;
    @Autowired
    private UserDetailService userDetailService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private AuthProperties authProperties;
    @Autowired
    private AuthWebResponseExceptionTranslator exceptionTranslator;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        // 客户端从认证服务器获取令牌的时候，必须使用client_id为xun，client_secret为123456的标识来获取；
        // 该client_id支持password模式获取令牌，并且可以通过refresh_token来获取新的令牌；
        // 在获取client_id为xun的令牌的时候，scope只能指定为all，否则将获取失败；
        // 注：如果需要指定多个client，可以继续使用withClient配置。
        // ##############版本1###############
//        clients.inMemory()
//                .withClient("xun")
//                .secret(passwordEncoder.encode("123456"))
//                .authorizedGrantTypes("password", "refresh_token")
//                .scopes("all");
        // ##############版本1###############
        // ###########版本2 升级版############
        ClientsProperties[] clientsArray = authProperties.getClients();
        InMemoryClientDetailsServiceBuilder builder = clients.inMemory();
        if (ArrayUtil.isNotEmpty(clientsArray)) {
            for (ClientsProperties client : clientsArray) {
                if (StrUtil.isBlank(client.getClient())) {
                    throw new Exception("client不能为空");
                }
                if (StrUtil.isBlank(client.getSecret())) {
                    throw new Exception("secret不能为空");
                }
                // 原式：String[] grantTypes = StringUtils.splitByWholeSeparatorPreserveAllTokens(client.getGrantType(), ",");
                String[] grantTypes = StrUtil.split(client.getGrantType(), ",");
                builder.withClient(client.getClient())
                        .secret(passwordEncoder.encode(client.getSecret()))
                        .authorizedGrantTypes(grantTypes)
                        .scopes(client.getScope());
            }
        }
        // ###########版本2 升级版############
    }

    @Override
    @SuppressWarnings("all")
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        endpoints.tokenStore(tokenStore())
                .userDetailsService(userDetailService)
                .authenticationManager(authenticationManager)
                .tokenServices(defaultTokenServices())
                .exceptionTranslator(exceptionTranslator);  //配置异常翻译器
    }

    @Bean
    public TokenStore tokenStore() {
        return new RedisTokenStore(redisConnectionFactory);
    }

    @Primary
    @Bean
    public DefaultTokenServices defaultTokenServices() {
        DefaultTokenServices tokenServices = new DefaultTokenServices();
        tokenServices.setTokenStore(tokenStore());
        tokenServices.setSupportRefreshToken(true); //开启刷新令牌的支持
        // ##############版本1###############
//        tokenServices.setAccessTokenValiditySeconds(60 * 60 * 24);       //令牌有效时间
//        tokenServices.setRefreshTokenValiditySeconds(60 * 60 * 24 * 7);  //刷新令牌有效时间
        // ##############版本1###############
        // ###########版本2 升级版############
        tokenServices.setAccessTokenValiditySeconds(authProperties.getAccessTokenValiditySeconds());       //令牌有效时间
        tokenServices.setRefreshTokenValiditySeconds(authProperties.getRefreshTokenValiditySeconds());  //刷新令牌有效时间
        // ##############版本1###############
        // ###########版本2 升级版############
        return tokenServices;
    }
}